const db = require("../db/util");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("../config")
let reguser = (req, res) => {
  let userInfo = req.body;

  // 判断用户名是否存在
  let sqlSelectUsername = "SELECT * FROM ev_users WHERE username=?";
  db.query(sqlSelectUsername, [userInfo.username], (err, result) => {
    if (err) {
      return res.cc(err.message);
    }

    if (result.length > 0) {
      return res.cc("注册失败! ");
    }
    userInfo.password = bcrypt.hashSync(userInfo.password, 10);

    //如用户名不存在则进行添加
    let sqlInsertUser = "insert into ev_users set ?";
    db.query(
      sqlInsertUser,
      { username: userInfo.username, password: userInfo.password },
      (err, result) => {
        if (err) {
          return res.cc(err.message);
        }

        //返回影响行数不等于零 添加成功
        if (result.affectedRows > 0) {
          return res.cc("注册成功", 0);
        }
      }
    );
  });
};


//判断登录
let login = (req, res) => {
  //查询用户
  let getuser = "select * from ev_users where username=?";
  db.query(getuser, [req.body.username], (err, result) => {
    if (err) return res.cc(err.message);

    //判断是否存在
    if (result.length == 0) {
      return res.cc("登录失败！");
    }
    let flag = bcrypt.compareSync(req.body.password, result[0].password);
    //判断登录是否成功
    if (!flag) {
      return res.cc("登录失败！");
    }

    //验证成功后 将用户数据存储token 但是要剔除出密码和头像
    const user = {...result[0],password: '', user_pic: ''}
    const token = jwt.sign(user , config.secretKey , {expiresIn: '10h'});
    
    //token生成后 将数据返回
    res.send({
      status:0,
      message:"登录成功",
      token:"Bearer "+token
    });
  });
};

module.exports = {
  reguser,
  login,
};
